import store from '@/store'
// eslint-disable-next-line
import { BasicLayout, BlankLayout, PageView, RouteView } from '@/layouts'

// 前端路由表
const constantRouterComponents = {
  // 基础页面 layout 必须引入
  BasicLayout: BasicLayout,
  BlankLayout: BlankLayout,
  RouteView: RouteView,
  PageView: PageView,
  'admin.admin': () => import('@/views/admin/admin/index'),
  'admin.admin.detail': () => import('@/views/admin/admin/detail'),
  'admin.role': () => import('@/views/admin/role/index'),
  'admin.resource': () => import('@/views/admin/resource/index'),
  'admin.log': () => import('@/views/admin/log/index'),
  'dashboard': () => import('@/views/dashboard/index')
}

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*', redirect: '/404', hidden: true
}

const allowRouters = {
  '/403': () => import(/* webpackChunkName: "error" */ '@/views/exception/403'),
  '/404': () => import(/* webpackChunkName: "error" */ '@/views/exception/404'),
  '/500': () => import(/* webpackChunkName: "error" */ '@/views/exception/500')
}

// 根级菜单
const rootRouter = {
  key: '',
  name: 'index',
  path: '',
  component: 'BasicLayout',
  redirect: '/dashboard',
  meta: {
    title: '首页'
  },
  children: []
}

/**
 * 动态生成菜单
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = () => {
  return new Promise((resolve) => {
    const auth = store.getters.auth
    const menuNav = []
    const childrenNav = []
    //      后端数据, 根级树数组,  根级 PID
    listToTree(auth.rules.filter((rule) => rule.type === 1), childrenNav, 0)
    rootRouter.redirect = childrenNav[0] && childrenNav[0].path
    rootRouter.children = childrenNav
    menuNav.push(rootRouter)
    const routers = generator(menuNav)
    routers.push(notFoundRouter)

    auth.rules.forEach(item => {
      if (item.type !== 1) {
        const path = item.path || item.uri
        routers.push({
          path: path,
          hidden: true,
          component: (constantRouterComponents[item.resource] || (() => import('@/views/exception/build-page')))
        })
      }
    })

    Object.keys(allowRouters).forEach(uri => {
      routers.push({
        path: uri,
        hidden: true,
        component: allowRouters[uri]
      })
    })
    resolve(routers)
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const { title, show, hideChildren, hiddenHeaderContent, target, icon, keepAlive } = item.meta || {}
    const currentRouter = {
      resource: item.resource,
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || `${parent && parent.path || ''}/${item.key}`,
      // 路由名称，建议唯一
      name: item.name || item.key || '',
      redirect: item.children && item.children.length > 0 ? item.children[0].path : undefined,
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component || item.key],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      // component: (constantRouterComponents[item.component || item.key]) || (() => import(`@/views/${item.component}`)),
      // 该路由对应页面的 组件 :方案3 (功能开发中)
      component: (constantRouterComponents[item.component || item.resource || item.path]) || (item.children && RouteView) || (() => import('@/views/exception/build-page')),

      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: {
        title: title,
        icon: icon || undefined,
        hiddenHeaderContent: hiddenHeaderContent,
        target: target,
        permission: item.name,
        keepAlive: keepAlive
      }
    }
    // 是否设置了隐藏菜单
    if (show === false) {
      currentRouter.hidden = true
    }
    // 是否设置了隐藏子菜单
    if (hideChildren) {
      currentRouter.hideChildrenInMenu = true
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.pid === parentId) {
      const child = {
        data: { ...item },
        title: item.title,
        meta: {
          title: item.title,
          icon: item.icon,
          show: item.type === 1 && item.status === 1,
          keepAlive: item.keepAlive || false
        },
        resource: item.resource,
        path: item.path || item.uri,
        key: item.id,
        children: []
      }
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id)
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // 加入到树中
      tree.push(child)
    }
  })
}
